package com.tarena.luban.demo.gateway.filters;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.luban.demo.gateway.ex.GatewayException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
public class AuthenticationFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try{
            //封装检查token逻辑
            checkToken(exchange);
        }catch (GatewayException e){
            log.info("异常",e);
            return Mono.error(e);
        }
        //正常向后流转
        return chain.filter(exchange);
    }

    private void checkToken(ServerWebExchange exchange) throws GatewayException {
        ServerHttpRequest request = exchange.getRequest();
        List<String> token = request.getQueryParams().get("token");
        if (CollectionUtils.isEmpty(token)){
            throw new GatewayException("您没有携带token");
        }
        String tokenValue = token.get(0);
        if (StringUtils.isEmpty(tokenValue)){
            throw new GatewayException("您的token值为空");
        }
        boolean match=tokenValue.matches("\\d{10}");
        if (!match){
            throw new GatewayException("您得token值格式不正确");
        }
    }
}
